import {
  addArticleInclusion,
  cancelArticleInclusion,
  queryArticleListByColumnId,
} from '@/service/article-column';
import type { ActionType } from '@ant-design/pro-components';
import { ProList } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { App, Button, message } from 'antd';
import type { Key } from 'react';
import { useRef, useState } from 'react';
import AddColumnModal from './components/AddColumnModal';

const ColumnDetail: React.FC = () => {
  const { id } = useParams();
  const { modal } = App.useApp();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [addOpen, setAddOpen] = useState<boolean>(false);

  // 添加文章收录至专栏 - 弹窗
  const prevAddColumn = () => {
    setAddOpen(true);
  };

  // 添加文章收录至专栏 - 提交
  const addColumn = async (ids) => {
    const res = await addArticleInclusion({
      columnId: id,
      articleIds: ids,
    });

    if (res) {
      message.success('操作成功');
      setAddOpen(false);
      actionRef?.current?.reloadAndRest();
    }
  };

  // 取消收录
  const unLink = (ids) => {
    modal.confirm({
      title: '删除提示',
      content: `确定取消收录？取消后文章不会被删除，仅删除关联关系`,
      onOk: async () => {
        const res = await cancelArticleInclusion({
          columnId: id,
          articleIds: ids,
        });

        if (res) {
          message.success('操作成功');
          actionRef?.current?.reloadAndRest();
        }
      },
    });
  };

  const tableSearch = async (params) => {
    let values = {
      articleTitle: params.title,
      pageNum: params.current,
      pageSize: params.pageSize,
    };

    const res = await queryArticleListByColumnId(id, values);

    return { success: true, data: res?.list || [], total: res?.total || 0 };
  };

  return (
    <>
      <ProList
        rowKey={item => item.id}
        actionRef={actionRef}
        request={tableSearch}
        editable={{}}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys: Key[]) => setSelectedRowKeys(keys),
        }}
        search={{}}
        metas={{
          title: {
            dataIndex: 'title',
            title: '文章名称',
            search: true,
          },
          description: {
            dataIndex: 'description',
            search: false,
          },
          subTitle: {
            dataIndex: 'createdTime',
            search: false,
          },
          actions: {
            cardActionProps: 'extra',
            render: (text, row) => [
              <Button type="link" key="link" danger onClick={() => unLink([row.id])}>
                取消收录
              </Button>,
            ],
            search: false,
          },
        }}
        toolbar={{
          actions: [
            <Button type="primary" key="add" onClick={() => prevAddColumn()}>
              收录至专栏
            </Button>,
            <Button type="primary" key="delete" danger onClick={() => unLink(selectedRowKeys)}>
              勾选取消收录
            </Button>,
          ],
        }}
      />
      <AddColumnModal open={addOpen} onOpenChange={setAddOpen} onFinish={addColumn} />
    </>
  );
};

export default ColumnDetail;
